package models;

import java.util.Date;

import models.mappers.InviteRewardMapper;
import models.mappers.UserIngotRecordMapper;
import models.mappers.fund.BuyerDepositRecordMapper;

import org.apache.ibatis.session.SqlSession;
import org.joda.time.DateTime;

import com.aton.db.SessionFactory;
import com.aton.util.MixHelper;

public class InviteReward {
	public Long id;
	public Long userid;
	public Long buyercount;
	public String hasrecive;
	public Long allcount;
	public String startDay;
	public String endDay;
	
	public static InviteReward getRewardByUserId(long id2) {
		// TODO Auto-generated method stub
		SqlSession ss=SessionFactory.getSqlSession();
		try{
			InviteRewardMapper mapper=ss.getMapper(InviteRewardMapper.class);
			return mapper.selectRewardByUserId(id2);
		}finally{
			ss.close();
		}
	}

	public static boolean saveRecive(InviteReward reward,String type,Long count) {
		// TODO Auto-generated method stub
		SqlSession ss=SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			InviteRewardMapper Invitemapper=ss.getMapper(InviteRewardMapper.class);
			Invitemapper.saveRecive(reward);
			Date now = DateTime.now().toDate();
			/*
			 * 将金币直接发给买手
			 */
			String memo = MixHelper.format("买手领取邀请奖励，领取类型为[{}]", type);
			UserIngotRecordMapper ingotMapper = ss.getMapper(UserIngotRecordMapper.class);
			// 获取上一次的金币记录计算结余
			UserIngotRecord lastRecord = ingotMapper.selectLastRecord(reward.userid);
			UserIngotRecord record = UserIngotRecord.newInstance(reward.userid, lastRecord).plus(count).memo(memo)
					.createTime(now);
			ingotMapper.insert(record);
			// 设置用户缓存中的本金余额
			User buyerCache = User.findByIdWichCache(reward.userid);
			buyerCache.deposit(record.balance).updateCache();
			ss.commit();
		}catch(Exception e){
			e.printStackTrace();
			ss.rollback();
			return false;
		}finally{
			ss.close();
		}
		return true;
	}
	/**
	 * 保存奖励记录
	 * @param reward
	 */
	public static void saveReWard(InviteReward reward) {
		// TODO Auto-generated method stub
		SqlSession ss=SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			InviteRewardMapper Invitemapper=ss.getMapper(InviteRewardMapper.class);
			Invitemapper.saveReWard(reward);
			ss.commit();
		}catch(Exception e){
			e.printStackTrace();
			ss.rollback();
		}finally{
			ss.close();
		}
	}

	public static void updateReWard(InviteReward reward) {
		// TODO Auto-generated method stub
		SqlSession ss=SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			InviteRewardMapper Invitemapper=ss.getMapper(InviteRewardMapper.class);
			Invitemapper.updateReWard(reward);
			ss.commit();
		}catch(Exception e){
			e.printStackTrace();
			ss.rollback();
		}finally{
			ss.close();
		}
	}
	
}
